package com.vietnam.power.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.vietnam.power.constant.AppConfigurationConstant;
import com.vietnam.power.domain.FileUpload;
import com.vietnam.power.service.FileService;

@Controller
public class CommonController {

	@Autowired
	private FileService fileService;

	@RequestMapping(value = "/loadImage", method = RequestMethod.GET)
	public void loadImage(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false, value = "type") String type,
			@RequestParam(required = false, value = "fileId") int fileId) throws IOException {
		// get absolute path of the application
		String appPath = request.getSession().getServletContext().getRealPath("/");

		// get file path from database
		String filePath = AppConfigurationConstant.FILE_UPLOAD.FILE_UPLOAD_ROOT_FOLDER + File.separator;

		FileUpload fu = fileService.getFileById(fileId);
		if (StringUtils.equalsIgnoreCase(type, AppConfigurationConstant.FILE_UPLOAD.FILE_THUMB)) {
			filePath += fu.getThumbName();
		} else if (StringUtils.equalsIgnoreCase(type, AppConfigurationConstant.FILE_UPLOAD.FILE_FULL_SIZE)) {
			filePath += fu.getFileName();
		}
		// construct the complete absolute path of the file
		String fullPath = appPath + filePath;

		byte[] bytes = Files.readAllBytes(Paths.get(fullPath));
		// get MIME type of the file
		String mimeType = request.getSession().getServletContext().getMimeType(fullPath);
		if (mimeType == null) {
			// set to binary type if MIME mapping not found
			mimeType = "image/jpeg";
		}
		// set content attributes for the response
		response.setContentType(mimeType);
		// get output stream of the response
		response.getOutputStream().write(bytes);
	}
}
